package cn.engage.basic.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
 * 发送qq邮件工具类
 */
@Component
public class EmailUtil implements ApplicationContextAware {

    public static ApplicationContext context;

    /**
     * 获取工厂
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     * 简单发送
     *
     * @param to      发送地址
     * @param title    邮件标题
     * @param message 邮件内容
     */
    public static void simpleSend(String to, String title, String message) {
        //通过上下文对象根据bean id获取bean对象  JavaMailSender的beanid是mailSender
        JavaMailSender javaMailSender = (JavaMailSender) context.getBean("mailSender");
        SimpleMailMessage simpleMessage = new SimpleMailMessage();
        // 设置发件人邮箱
        simpleMessage.setFrom("1075053212@qq.com");
        // 设置收件人qq邮箱
        simpleMessage.setTo(to);
        // 设置邮件标题
        simpleMessage.setSubject(title);
        // 设置文本内容
        simpleMessage.setText(message);
        // 发送邮件
        javaMailSender.send(simpleMessage);
    }
}
